#include "WorkerThread.h"
#include "Logger.h"
#include "Singleton.h"
#include "Task.h"
#include "ThreadPool.h"

using namespace ddserver::thread;
using namespace ddserver::utility;

WorkerThread::WorkerThread() : Thread()
{

}

WorkerThread::~WorkerThread()
{

}

void WorkerThread::cleanup(void* ptr)
{
    log_info("worker thread cleanup handler:%x",ptr);
}

void WorkerThread::run()
{
   sigset_t mask; 
   if(0 != sigfillset(&mask))
   {
        log_error("worker thread sigfillset failed");
   }

   if (0 != pthread_sigmask(SIG_SETMASK,&mask,NULL))
   {
        log_error("worker thread pthread_sigmask failed");
   }
   pthread_cleanup_push(cleanup, this);

   while (true)
   {
        m_mutex.lock();
        
        while (m_task == NULL)
        {
            m_cond.wait(&m_mutex);
        }
        log_info("m_cond wait work[%x],this[%x]",m_task,this);
        m_mutex.unlock();

        int old_state = 0;
        int rc = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,&old_state);
        
        m_task->run();
        m_task->destroy();
        m_task = NULL;

        Singleton<ThreadPool>::instance()->move_to_idle_list(this); // when the thread is run over,move the thread to the m_list_idle

        rc = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,&old_state);
        pthread_testcancel();
   }
   pthread_cleanup_pop(1);
}